/*
 * @CreatDate: 2020-10-12 18:31:00
 * @Describe: 流程图绘制基类
 * 调用此基类的前提需要先引入jQuery,lodash,backbone,joint,当前已在index.html上引入
 *
 * API文档：https://resources.jointjs.com/mmap/joint.html
 * JointJS入门教程：https://resources.jointjs.com/docs/jointjs/v3.2/joint.html
 */

import './index.scss'
import dagre from 'dagre'
import graphlib from 'graphlib'
// import { Logger } from "runjs/lib/common"
import { parseInt } from 'lodash'
import { nodeName } from 'jquery'

class Workflow {
  constructor(el, config) {
    this.config = {
      defaultRouter: 'orthogonal', // orthogonal,manhattan,metro,normal
      ...config
    }
    this.el = el
    this.init(config.width, config.height, config.color, config.image, config.gridSize)
  }
  init(width, height, color, image, gridSize) {
    this.graph = new joint.dia.Graph()
  
    this.keyboard = new joint.ui.Keyboard()
    this.paper = new joint.dia.Paper({
      width: width,
      height: height,
      gridSize: gridSize,
      clickThreshold: 1,
      drawGrid: {
        name: 'doubleMesh',
        args: [
          {
            color: '#dedede', //栅格点颜色
            scaleFactor: 1,
            thickness: 1 //栅格点大小
          },
          {
            color: '#dedede', //栅格点颜色
            scaleFactor: 10,
            thickness: 2 //栅格点大小
          }
        ]
      },
      background: {
        color: color,
        image: image,
        size: { width: width, height: height }
      },
      model: this.graph,
      defaultLink: new joint.dia.Link({
        markup: [
          '<path class="connection" stroke-dasharray="1,0" stroke="#1a8cff" d="M 0 0 0 0"/>',
          '<path class="marker-source" fill="#1a8cff" stroke="#1a8cff" d="M 0 0 0 0"/>',
          '<path class="marker-target" fill="#1a8cff" stroke="#1a8cff" d="M 0 0 0 0"/>',
          '<path class="connection-wrap" d="M 0 0 0 0"/>',
          '<g class="labels" />',
          '<g class="marker-vertices"/>',
          '<g class="marker-arrowheads"/>',
          '<g class="link-tools" />'
        ].join(''),
        attrs: {
          ".marker-target": { fill: "#1a8cff", d: "M 10 0 L 0 5 L 10 10 z" }
        },
        bpmnType: 'SequenceFlow',
        connector: { name: 'normal' }
      }),
      interactive: { linkMove: false },
      async: true,
      sorting: joint.dia.Paper.sorting.APPROX,
      linkPinning: true, // 连线必须连到某个元素，即不允许连到空白处
      snapLinks: {
        radius: 25 // 距离元素连接点25像素时自动连接上
      },
      defaultRouter: {
        name: this.config.defaultRouter
      },
      // defaultConnectionPoint: { name: 'boundary' },
      perpendicularLinks: true,
      restrictTranslate: false, //设定元素不能拖出画布
    })
    // this.paper.freeze()
    let arr = []
    let ed
    this.paper.on({
      'element:pointerdblclick': (elementView, evt) => {
        evt.preventDefault();
        // this.graph.removeCells(this.cell)
        // joint.ui.TextEditor.edit(evt.target, {
        //   cellView: elementView,
        //   textProperty: ['attrs', 'label', 'text'],
        //   annotationsProperty: ['attrs', 'label', 'annotations'],
        // });
        // $('.joint-text-editor').css({
        //   position: 'relative',
        //   top: evt.offsetY,
        //   left: evt.offsetX,
        //   // opacity: 0
        // });
      },
      'blank:pointerdown': (evt, x, y) => {
        joint.ui.TextEditor.close();
        if (this.keyboard.isActive('shift ctrl command', evt)) {
          if (this.selection) {
            this.selection.startSelecting(evt, x, y)
          }
        } else {
          if (this.selection) {
            $('#modifyFormat').css('display', 'none')
            $('#modifyImage').css('display', 'none')
            $('#modifyLink').css('display', 'none')
            $('#modifyCanvas').css('display', 'block')
            getcanvasSize()
            setscaleplate()
            this.selection.cancelSelection()
          }
          this.paperScroller.startPanning(evt, x, y)
        }
      },
      'element:pointerdown': (cellView, evt) => {
        if (this.keyboard.isActive('ctrl meta', evt)) {
          if (this.selection) {
            this.selection.collection.add(cellView.model)
            arr.push(cellView.model)
          }
        }
      },
      // 点击元素事件
      'cell:pointerdown': (cellView, evt, x, y) => {
       
        var cell = cellView.model
        this.cell = cell
        if (cell.get('type') != 'standard.Rectangle') {
          $('.rounded').hide()
          $('.filter').hide()
        } else {
          $('.rounded').show()
          $('.filter').show()
        }
        if (cell.get('type').startsWith('standard')) {
          // 当点击元素不是图片类型的元素时
          // TODO 设置属性
          if (cell.get('type') !== 'standard.Image') {
            let modifyFormatData
            if (cell.get('type') === 'standard.TextBlock') {
              modifyFormatData = this.modifyFormatData = {
                lcType: true,
                cell: cellView.model,
                height: Math.ceil(cell.get('size').height),
                width: cell.get('size').width,
                hierarchy: cell.get('attrs')['root'].hierarchy,
                incident: cell.get('attrs')['root'].incident,
                incidentData: cell.get('attrs')['root'].incidentData,
                dialogColor: cell.get('attrs')['root'].dialogColor,
                dialogWidth: cell.get('attrs')['root'].dialogWidth,
                dialogHeight: cell.get('attrs')['root'].dialogHeight,
                stroke: cell.get('attrs')['body'].stroke,
                fillOpacity: cell.get('attrs')['body'].fillOpacity,
                bodyfill: cell.get('attrs')['body'].fill,
                strokeDasharray: cell.get('attrs')['body'].strokeDasharray,
                rx: cell.get('attrs')['body'].rx,
                strokeWidth: cell.get('attrs')['body'].strokeWidth,
                text: cell.get('attrs')['label'].text,
                fontSize: cell.get('attrs')['label']['style'].fontSize,
                labelfill: cell.get('attrs')['label']['style'].color,
                fontWeight: cell.get('attrs')['label']['style'].fontWeight,
                fontStyle: cell.get('attrs')['label']['style'].fontStyle,
                fontFamily: cell.get('attrs')['label']['style'].fontFamily,
                // filter: {
                //   dx: cell.get('attrs')['rect'].filter.args.dx,
                //   dy: cell.get('attrs')['rect'].filter.args.dy,
                //   blur: cell.get('attrs')['rect'].filter.args.blur
                // }
              }
            } else if (cell.get('type') === 'standard.Cylinder') {
              modifyFormatData = this.modifyFormatData = {
                lcType: true,
                cell: cellView.model,
                height: Math.ceil(cell.get('size').height),
                width: cell.get('size').width,
                hierarchy: cell.get('attrs')['root'].hierarchy,
                incident: cell.get('attrs')['root'].incident,
                incidentData: cell.get('attrs')['root'].incidentData,
                dialogColor: cell.get('attrs')['root'].dialogColor,
                dialogWidth: cell.get('attrs')['root'].dialogWidth,
                dialogHeight: cell.get('attrs')['root'].dialogHeight,
                stroke: cell.get('attrs')['body'].stroke,
                fillOpacity: cell.get('attrs')['body'].fillOpacity,
                bodyfill: cell.get('attrs')['body'].fill,
                strokeDasharray: cell.get('attrs')['body'].strokeDasharray,
                rx: cell.get('attrs')['body'].rx,
                strokeWidth: cell.get('attrs')['body'].strokeWidth,
                text: cell.get('attrs')['label'].text.replace(/\t\n/g, ""),
                fontSize: cell.get('attrs')['label'].fontSize,
                labelfill: cell.get('attrs')['label'].fill,
                fontWeight: cell.get('attrs')['label'].fontWeight,
                fontStyle: cell.get('attrs')['label'].fontStyle,
                fontFamily: cell.get('attrs')['label'].fontFamily,
                fontAlign: cell.get('attrs')['label'].textAnchor,
                // textOpacity: cell.get('attrs')['label']['style'].opacity,
                // letterSpacing: cell.get('attrs')['label']['style'].letterSpacing,
                // filter: {
                //   dx: '',
                //   dy: '',
                //   blur: ''
                // }
              }
            } else {
              modifyFormatData = this.modifyFormatData = {
                lcType: true,
                cell: cellView.model,
                height: Math.ceil(cell.get('size').height),
                width: cell.get('size').width,
                hierarchy: cell.get('attrs')['root'].hierarchy,
                incident: cell.get('attrs')['root'].incident,
                incidentData: cell.get('attrs')['root'].incidentData,
                dialogColor: cell.get('attrs')['root'].dialogColor,
                dialogWidth: cell.get('attrs')['root'].dialogWidth,
                dialogHeight: cell.get('attrs')['root'].dialogHeight,
                stroke: cell.get('attrs')['body'].stroke,
                fillOpacity: cell.get('attrs')['body'].fillOpacity,
                bodyfill: cell.get('attrs')['body'].fill,
                strokeDasharray: cell.get('attrs')['body'].strokeDasharray,
                rx: cell.get('attrs')['body'].rx,
                strokeWidth: cell.get('attrs')['body'].strokeWidth,
                text: cell.get('attrs')['label'].text.replace(/\t\n/g, ""),
                fontSize: cell.get('attrs')['label'].fontSize,
                labelfill: cell.get('attrs')['label'].fill,
                fontWeight: cell.get('attrs')['label'].fontWeight,
                fontStyle: cell.get('attrs')['label'].fontStyle,
                fontFamily: cell.get('attrs')['label'].fontFamily,
                fontAlign: cell.get('attrs')['label'].textAnchor,
                textOpacity: cell.get('attrs')['label']['style'].opacity,
                letterSpacing: cell.get('attrs')['label']['style'].letterSpacing,
                // filter: {
                //   dx: cell.get('attrs')['rect'].filter.args.dx,
                //   dy: cell.get('attrs')['rect'].filter.args.dy,
                //   blur: cell.get('attrs')['rect'].filter.args.blur
                // }
              }
            }
            getElFormatData(modifyFormatData)
            $('#modifyImage').css('display', 'none')
            $('#modifyLink').css('display', 'none')
            $('#modifyFormat').css('display', 'block')
            $('#modifyCanvas').css('display', 'none')
            console.log(modifyFormatData);
          } else if (cell.get('type') === 'standard.Image') {
            let imageFormatData = this.imageFormatData = {
              lcType: true,
              cell: cellView.model,
              scaling: 1,
              height: Math.ceil(cell.get('size').height),
              width: Math.ceil(cell.get('size').width),
              xlinkHref: cell.get('attrs')['image'].xlinkHref,
              hierarchy: cell.get('attrs')['root'].hierarchy,
              incident: cell.get('attrs')['root'].incident,
              incidentData: cell.get('attrs')['root'].incidentData,
              dialogColor: cell.get('attrs')['root'].dialogColor,
              dialogWidth: cell.get('attrs')['root'].dialogWidth,
              dialogHeight: cell.get('attrs')['root'].dialogHeight,
            }
            getElFormatImgData(imageFormatData)
            $('#modifyFormat').css('display', 'none')
            $('#modifyLink').css('display', 'none')
            $('#modifyImage').css('display', 'block')
            $('#modifyCanvas').css('display', 'none')
          }
        } else if (cell.get('type') === 'link') {
          $('#modifyImage').css('display', 'none')
          $('#modifyCanvas').css('display', 'none')
          $('#modifyFormat').css('display', 'none')
          $('#modifyLink').css('display', 'block')

          if (cell.get('attrs')['.connection'] === undefined) {
            this.changeLink(cell, '#1a8cff', '0', 1)
            this.changeLinkType(cell, 'rounded')
            let data = {
              text: '',
              fontSize: '12px',
              color: '#000',
              fontWeight: 'Normal',
              fontStyle: 'Normal',
              fontFamily: 'SimSun'
            }
            this.changeLinkWordage(cell, data)
          }
          let linkStyleType
          if (cell.get('attrs')['.connection']['stroke-dasharray'] == 0) {
            linkStyleType = '1,0'
          } else if (cell.get('attrs')['.connection']['stroke-dasharray'] == 5) {
            linkStyleType = '5,5'
          } else if (cell.get('attrs')['.connection']['stroke-dasharray'] == 10) {
            linkStyleType = '10,10'
          } else {
            linkStyleType = '1,0'
          }
          let linkFormatData = this.linkFormatData = {
            cell: cellView.model,
            style: cell.connector().name,
            thickness: cell.get('attrs')['.connection']['stroke-width'],
            linkStyle: linkStyleType,
            stroke: cell.get('attrs')['.connection'].stroke,
            color: cell.get('labels')[0].attrs.text.fill,
            fontSize: parseInt(cell.get('labels')[0].attrs.text.fontSize),
            fontWeight: cell.get('labels')[0].attrs.text.fontWeight,
            fontStyle: cell.get('labels')[0].attrs.text.fontStyle,
            fontFamily: cell.get('labels')[0].attrs.text.fontFamily,
            text: cell.get('labels')[0].attrs.text.text,
          }

          if (cell.get('attrs')['.marker-source'] != undefined) {
            linkFormatData.AfterArrow = cell.get('attrs')['.marker-source'].d != '' ? 1 : 0
          } else {
            linkFormatData.AfterArrow = 0
          }
          if (cell.get('attrs')['.marker-target'] != undefined) {
            linkFormatData.BeforeArrow = cell.get('attrs')['.marker-target'].d != '' ? 1 : 0
          } else {
            linkFormatData.BeforeArrow = 0
          }
          getElFormatLinkData(linkFormatData)
        }
      },
      // 松开鼠标点击事件
      'cell:pointerup': (cellView, evt, x, y) => {
        var cell = cellView.model
        this.cell = cell
        getcanvasSize()
        setscaleplate()
      },
      'cell:contextmenu': (cellView, evt, x, y) => {
        joint.ui.TextEditor.close();
        openMenu(evt, cellView)
      },
    })
    this.keyboard.on({
      'ctrl+c': function (evt) {
        evt.preventDefault()
        this.selection.collection.add(this.cell);
        this.clipboard.copyElements(this.selection.collection, this.graph);
      },
      'ctrl+x': function (evt) {
        evt.preventDefault()
        this.selection.collection.add(this.cell);
        this.clipboard.cutElements(this.selection.collection, this.graph);
      },
      'ctrl+v': function (evt) {
        evt.preventDefault()
        var pastedCells = this.clipboard.pasteCells(this.graph, {
          translate: { dx: 5, dy: 5 },
          useLocalStorage: true
        });
      },
      'ctrl+a': function () {
        this.selection.collection.reset(this.graph.getElements());
      },
      'ctrl+z': function () {
        this.commandManager.undo()
        this.selection.cancelSelection()
      },
      'ctrl+y': function () {
        this.commandManager.redo()
        this.selection.cancelSelection()
      },
      'ctrl+s': function (evt) {
        evt.preventDefault();
        clickSaveJson()
      },
      'delete backspace': function (evt) {
        evt.preventDefault()
        this.graph.removeCells(this.cell)
      },
      'keydown:shift': function (evt) {
        this.paperScroller.setCursor('crosshair')
      },
      'keyup:shift': function () {
        this.paperScroller.setCursor('grab')
      },
      'ctrl+plus': function (evt) {
        evt.preventDefault();
        this.paperScroller.zoom(0.2, { max: 1, grid: 0.2 });
      },
      'ctrl+minus': function (evt) {
        evt.preventDefault();
        this.paperScroller.zoom(-0.2, { min: 0.2, grid: 0.2 });
      },
    }, this)
    this.graph.on('change', (cell, opt) => {
      if (cell.isLink() || !opt.textEditor) return;
    })
    this.addPaperScroller()
    this.addNavigation()
    this.addCommandManager()
    this.addSnaplines()
    this.elementClick()
    this.addSelection()
    this.zoom('0.95')
  }
  /* ********************修改元件属性开始******************** */
  changeLink(cell, stroke, dasharray, width) {
    cell.attr({
      '.connection': { stroke: stroke, 'stroke-dasharray': (dasharray.split(',')[0], dasharray.split(',')[1]), 'stroke-width': width }
    })
  }
  changeArrowsLeft(cell, type, val) {
    if (type) {
      cell.attr({
        '.marker-source': { fill: val, d: "M 10 0 L 0 5 L 10 10 z" },
      })
    } else {
      cell.attr({
        '.marker-source': { fill: val, d: "" },
      })
    }
  }
  changeArrowsRight(cell, type, val) {
    if (type) {
      cell.attr({
        '.marker-target': { fill: val, d: "M 10 0 L 0 5 L 10 10 z" },
      })
    } else {
      cell.attr({
        '.marker-target': { fill: val, d: "" },
      })
    }
  }
  changeLinkType(cell, type) {
    cell.connector({ name: type })
  }
  changeLinkWordage(cell, data) {
    cell.labels([{
      attrs: {
        text: {
          text: data.text,
          fontSize: data.fontSize + 'px',
          fill: data.color,
          fontWeight: data.fontWeight,
          fontStyle: data.fontStyle,
          fontFamily: data.fontFamily
        }
      }
    }])
  }
  changeWidth(cell, val) { //元素大小
    console.log(val);
    this.breakedText(cell, cell.attributes.attrs.label.text, '')
    cell.size(val.width, val.height)
    this.changeFontalign(cell,val)
 
  }
  changeBodyFill(cell, color) { // 背景颜色
    cell.attr('body/fill', color)
  }
  changeFillOpacity(cell, num) { // 背景透明度
    cell.attr('body/fillOpacity', num)
  }
  changeBorderColor(cell, color) { // 边框颜色
    cell.attr('body/stroke', color)
  }
  changeStrokeWidth(cell, num) { // 边框大小
    cell.attr('body/strokeWidth', num)
  }
  changeStrokeDasharray(cell, val) { // 边框样式
    cell.attr('body/strokeDasharray', val)
  }
  changeRx(cell, val) { // 边框圆角
    cell.attr('body/rx', val)
  }
  changeText(cell, val) { // 文字内容
    let sizeData = cell.attributes.size
    this.breakedText(cell, val, sizeData)
  }
  changeFontSize(cell, val) { // 文字大小
    if (cell.get('type') === 'standard.TextBlock') {
      cell.attr('label/style/fontSize', val)
    } else {
      cell.attr('label/fontSize', val)
    }
    this.breakedText(cell, cell.attributes.attrs.label.text, '')
  }
  changeLabelFill(cell, val) { // 文字颜色
    if (cell.get('type') === 'standard.TextBlock') {
      cell.attr('label/style/color', val)
    } else {
      cell.attr('label/fill', val)
    }
  }
  changeFontWeight(cell, val) { // 文字粗细
    if (cell.get('type') === 'standard.TextBlock') {
      cell.attr('label/style/fontWeight', val)
    } else {
      cell.attr('label/fontWeight', val)
    }
  }
  changeFontFamily(cell, val) { // 文字字体

    if (cell.get('type') === 'standard.TextBlock') {
      cell.attr('label/style/fontFamily', val)
    } else if (cell.get('type') === 'link') {
      cell.attr('label/style/fontFamily', val)
    } else {
      cell.attr('label/fontFamily', val)
    }
  }
  changeFontStyle(cell, val) { // 文字倾斜
    cell.attr('label/style/fontStyle', val)
  }
  changeFontalign(cell, val) {//文字对齐
    if (val.fontAlign == 'start') {
      this.changeFontLocation(cell, { x: 30, y: (val.height / 2) })
      // }
    } else if (val.fontAlign == 'middle') {
      this.changeFontLocation(cell, { x: (val.width / 2), y: (val.height / 2) })
    } else {
      this.changeFontLocation(cell, { x: val.width, y: (val.height / 2) })
    }
    cell.attr('label/textAnchor', val.fontAlign)
  }
  changeFontLocation(cell, val) {
    console.log('val', val);
    cell.attr('label/style/transform', `matrix(1,0,0,1,${val.x},${val.y})`)
  }
  changeTextOpacity(cell, val) {
    cell.attr('label/style/opacity', val)
  }
  changeletterSpacing(cell, val) {
    cell.attr('label/style/letterSpacing', val)
  }
  changeFilter(cell, val) { // 元素阴影
    let data = {
      name: 'dropShadow',
      args: {
        dx: val.dx,
        dy: val.dy,
        blur: val.blur
      }
    }

    cell.attr('rect/filter', data)
  }
  changeHierarchy(cell, val) { // 节点顺序
    cell.attr('root/hierarchy', val)
  }
  changeIncident(cell, val) { // 资源类型
    cell.attr('root/incident', val)
  }
  changeIncidentData(cell, val) { // 资源类型数据
    cell.attr('root/incidentData', val)
  }
  changedialogColor(cell, val) { // 弹出框样式
    cell.attr('root/dialogColor', val)
  }
  changedialogWidth(cell, val) { // 弹出框样式
    cell.attr('root/dialogWidth', val)
  }
  changedialogHeight(cell, val) { // 弹出框样式
    cell.attr('root/dialogHeight', val)
  }
  changexlinkHref(cell, val) {
    cell.attr('image/xlinkHref', val)
  }
  changeZindexTop(cell, opt) {
    cell.toFront(opt)
  }
  changeZindexBottom(cell, opt) {
    cell.toBack(opt)
  }
  changeIsNone(cell, val) {
    cell.attr('root/style/display', val)
  }
  /* ********************修改元件属性结束******************** */
  getPNG() {
    // return this.paper


  }

  getPraph() {
    return this.graph
  }

  // 渲染数据 cells:[]
  setData(cells) {
    this.graph.clear()
    this.graph.addCells(cells)
  }

  // 获取数据
  getData() {
    return this.graph.toJSON()
  }
  // 设置数据
  setFromData(json) {
    this.graph.fromJSON(json);
  }
  // 单击节点
  elementClick() {
    this.paper.on('cell:pointerclick', (cellView) => {
      // We don't want a Halo for links.
      if (cellView.model instanceof joint.dia.Link) return
      this.customHalo(cellView)
    })
  }

  customHalo(cellView) {
    let halo = new joint.ui.Halo({
      cellView: cellView,
      boxContent: false,
      clearAll: true
    })

    // 自定义操作面板
    // halo.removeHandle("clone")
    // halo.removeHandle("resize")
    // halo.removeHandle("rotate")
    // halo.removeHandle("fork")
    // halo.removeHandle("unlink")
    // halo.removeHandle("link")
    // halo.changeHandle("link", { icon: "/joint/img/link.png" })
    // halo.changeHandle("remove", { icon: "/joint/img/remove.png" })

    // halo.on("action:link:add", (link) => {
    //   console.log("连线成功，可以在此做业务逻辑处理")
    // })

    halo.on("action:remove:pointerup", () => {
      $('#modifyImage').css('display', 'none')
      $('#modifyLink').css('display', 'none')
      $('#modifyFormat').css('display', 'none')
      $('#modifyCanvas').css('display', 'block')
    })

    halo.on("action:resize:pointerup", (val) => {
      let cell = this.cell
      if (cell.get('type').startsWith('standard')) {
        // 当点击元素不是图片类型的元素时
        if (cell.get('type') !== 'standard.Image') {
          let modifyFormatData
          if (cell.get('type') === 'standard.TextBlock') {
            modifyFormatData = this.modifyFormatData = {
              lcType: true,
              cell: cellView.model,
              height: cell.get('size').height,
              width: cell.get('size').width,
              hierarchy: cell.get('attrs')['root'].hierarchy,
              incident: cell.get('attrs')['root'].incident,
              incidentData: cell.get('attrs')['root'].incidentData,
              dialogColor: cell.get('attrs')['root'].dialogColor,
              dialogWidth: cell.get('attrs')['root'].dialogWidth,
              dialogHeight: cell.get('attrs')['root'].dialogHeight,
              stroke: cell.get('attrs')['body'].stroke,
              fillOpacity: cell.get('attrs')['body'].fillOpacity,
              bodyfill: cell.get('attrs')['body'].fill,
              strokeDasharray: cell.get('attrs')['body'].strokeDasharray,
              rx: cell.get('attrs')['body'].rx,
              strokeWidth: cell.get('attrs')['body'].strokeWidth,
              text: cell.get('attrs')['label'].text.replace(/\t\n/g, ""),
              fontSize: cell.get('attrs')['label']['style'].fontSize,
              labelfill: cell.get('attrs')['label']['style'].color,
              fontWeight: cell.get('attrs')['label']['style'].fontWeight,
              fontStyle: cell.get('attrs')['label']['style'].fontStyle,
              fontFamily: cell.get('attrs')['label']['style'].fontFamily,
              // filter: {
              //   dx: cell.get('attrs')['rect'].filter.args.dx,
              //   dy: cell.get('attrs')['rect'].filter.args.dy,
              //   blur: cell.get('attrs')['rect'].filter.args.blur
              // }
            }
          } else {
            modifyFormatData = this.modifyFormatData = {
              lcType: true,
              cell: cellView.model,
              height: cell.get('size').height,
              width: cell.get('size').width,
              hierarchy: cell.get('attrs')['root'].hierarchy,
              incident: cell.get('attrs')['root'].incident,
              incidentData: cell.get('attrs')['root'].incidentData,
              dialogColor: cell.get('attrs')['root'].dialogColor,
              dialogWidth: cell.get('attrs')['root'].dialogWidth,
              dialogHeight: cell.get('attrs')['root'].dialogHeight,
              stroke: cell.get('attrs')['body'].stroke,
              fillOpacity: cell.get('attrs')['body'].fillOpacity,
              bodyfill: cell.get('attrs')['body'].fill,
              strokeDasharray: cell.get('attrs')['body'].strokeDasharray,
              rx: cell.get('attrs')['body'].rx,
              strokeWidth: cell.get('attrs')['body'].strokeWidth,
              text: cell.get('attrs')['label'].text.replace(/\t\n/g, ""),
              fontSize: cell.get('attrs')['label'].fontSize,
              labelfill: cell.get('attrs')['label'].fill,
              fontWeight: cell.get('attrs')['label'].fontWeight,
              fontStyle: cell.get('attrs')['label'].fontStyle,
              fontFamily: cell.get('attrs')['label'].fontFamily,
              fontAlign: cell.get('attrs')['label'].textAnchor,
              // filter: {
              //   dx: cell.get('attrs')['rect'].filter.args.dx,
              //   dy: cell.get('attrs')['rect'].filter.args.dy,
              //   blur: cell.get('attrs')['rect'].filter.args.blur
              // }
            }
            //  调整大小对齐
            if (modifyFormatData.fontAlign == 'start') {
              this.changeFontLocation(cell, { x: 30, y: (modifyFormatData.height / 2) })
            } else if (modifyFormatData.fontAlign == 'middle') {
              this.changeFontLocation(cell, { x: (modifyFormatData.width / 2), y: (modifyFormatData.height / 2) })
            } else {
              this.changeFontLocation(cell, { x: modifyFormatData.width, y: (modifyFormatData.height / 2) })
            }
            cell.attr('label/textAnchor', modifyFormatData.fontAlign)
          }
          getElFormatData(modifyFormatData)
          $('#modifyImage').css('display', 'none')
          $('#modifyLink').css('display', 'none')
          $('#modifyFormat').css('display', 'block')
          $('#modifyCanvas').css('display', 'none')
        } else if (cell.get('type') === 'standard.Image') {
          let imageFormatData = this.imageFormatData = {
            lcType: true,
            cell: cellView.model,
            height: parseInt(cell.get('size').height),
            width: parseInt(cell.get('size').width),
            xlinkHref: cell.get('attrs')['image'].xlinkHref,
            hierarchy: cell.get('attrs')['root'].hierarchy,
            incident: cell.get('attrs')['root'].incident,
            incidentData: cell.get('attrs')['root'].incidentData,
            dialogColor: cell.get('attrs')['root'].dialogColor,
            dialogWidth: cell.get('attrs')['root'].dialogWidth,
            dialogHeight: cell.get('attrs')['root'].dialogHeight,
          }
          getElFormatImgData(imageFormatData)
          $('#modifyFormat').css('display', 'none')
          $('#modifyLink').css('display', 'none')
          $('#modifyImage').css('display', 'block')
          $('#modifyCanvas').css('display', 'none')
        }
      } else if (cell.get('type') === 'link') {
        $('#modifyImage').css('display', 'none')
        $('#modifyCanvas').css('display', 'none')
        $('#modifyFormat').css('display', 'none')
        $('#modifyLink').css('display', 'block')

        if (cell.get('attrs')['.connection'] === undefined) {
          this.changeLink(cell, '#1a8cff', '0', 1)
          this.changeLinkType(cell, 'normal')
          let data = {
            text: '',
            fontSize: '12px',
            color: '#000',
            fontWeight: 'Normal',
            fontStyle: 'Normal',
            fontFamily: 'SimSun'
          }
          this.changeLinkWordage(cell, data)
        }
        let linkStyleType
        if (cell.get('attrs')['.connection']['stroke-dasharray'] == 0) {
          linkStyleType = '1,0'
        } else if (cell.get('attrs')['.connection']['stroke-dasharray'] == 5) {
          linkStyleType = '5,5'
        } else if (cell.get('attrs')['.connection']['stroke-dasharray'] == 10) {
          linkStyleType = '10,10'
        } else {
          linkStyleType = '1,0'
        }
        let linkFormatData = this.linkFormatData = {
          cell: cellView.model,
          style: cell.connector().name,
          thickness: cell.get('attrs')['.connection']['stroke-width'],
          linkStyle: linkStyleType,
          stroke: cell.get('attrs')['.connection'].stroke,
          color: cell.get('labels')[0].attrs.text.fill,
          fontSize: parseInt(cell.get('labels')[0].attrs.text.fontSize),
          fontWeight: cell.get('labels')[0].attrs.text.fontWeight,
          fontStyle: cell.get('labels')[0].attrs.text.fontStyle,
          fontFamily: cell.get('labels')[0].attrs.text.fontFamily,
          text: cell.get('labels')[0].attrs.text.text,
        }

        if (cell.get('attrs')['.marker-source'] != undefined) {
          linkFormatData.AfterArrow = cell.get('attrs')['.marker-source'].d != '' ? 1 : 0
        } else {
          linkFormatData.AfterArrow = 0
        }
        if (cell.get('attrs')['.marker-target'] != undefined) {
          linkFormatData.BeforeArrow = cell.get('attrs')['.marker-target'].d != '' ? 1 : 0
        } else {
          linkFormatData.BeforeArrow = 0
        }
        getElFormatLinkData(linkFormatData)
      }
    })

    halo.render()
  }

  // 对画布实现平移，滚动操作
  addPaperScroller() {
    this.paperScroller = new joint.ui.PaperScroller({
      paper: this.paper,
      autoResizePaper: true,
      scrollWhileDragging: false,
      padding: 0,
      cursor: 'pointer'
    })
    this.el.append(this.paperScroller.render().el)
  }

  // 添加小窗口
  addNavigation() {
    this.nav = new joint.ui.Navigator({
      width: 200,
      height: 150,
      paperScroller: this.paperScroller,
      padding: 0,
      zoom: {
        grid: 10,
        min: 1,
        max: 2
      }
    })
    this.el.append(this.nav.render().el)
  }


  // 拖拽面板
  addStencil(el, stencilItem) {
    this.stencil = new joint.ui.Stencil({
      paper: this.paper,
      width: 250,
      height: 480,
      layout: true
    })
    el.append(this.stencil.render().el)
    this.stencil.load(stencilItem)
    $('.stencil-paper-drag').remove()
  }

  // 操作面板
  addCommandManager() {
    this.commandManager = new joint.dia.CommandManager({
      graph: this.graph,
      cmdBeforeAdd: (cmdName, cell, graph, options) => {
        options = options || {}
        return !options.ignoreCommandManager
      }
    })
  }

  // 选择插件
  addSelection() {
    this.clipboard = new joint.ui.Clipboard({ useLocalStorage: false })
    this.selection = new joint.ui.Selection({
      paper: this.paper,
      useModelGeometry: true
    })

  }

  // 注册辅助线并开启
  addSnaplines() {
    this.snaplines = new joint.ui.Snaplines({ paper: this.paper })
    this.openSnaplines()
  }

  // 开启辅助线
  openSnaplines() {
    this.snaplines.startListening()
  }

  // 关闭辅助线
  closeSnaplines() {
    this.snaplines.stopListening()
  }

  // 清空画布
  clear() {
    this.graph.clear()
  }

  // 撤销
  undo() {
    this.commandManager.undo()
  }

  // 重做
  redo() {
    this.commandManager.redo()
  }

  // 打印
  print() {
    this.paper.print()
  }
  // openAsSVG
  openAsSVG() {
    // this.paper.openAsSVG()
    var downloadArea = this.graph.getBBox().inflate(20)
    this.paper.toSVG(function (svg) {
      var data = 'data:image/svg+xml,' + encodeURIComponent(svg)
      // var data = 'data:image/png;base64,' + encodeURIComponent(png)
      var fileName = '流程图.svg'
      joint.util.downloadDataUri(data, fileName)
    }.bind(), {
      // area: downloadArea,
      // preserveDimensions: true,
      // useComputedStyles: false,
      // stylesheet: [
      //   '.scalable * { vector-effect: non-scaling-stroke }',
      //   'svg { background-color: #ffffff }'
      // ].join('')
    })

  }
  // 放大
  zoom(val) {
    this.paperScroller.zoom(100, { max: 2, grid: 0.1 })
    if (parseInt(val) != parseInt(1)) {
      this.paperScroller.zoom(val, { max: 2, grid: 0.1 })
    }
  }
  // 全屏
  fullScreen() {
    const element = document.documentElement
    if (element.requestFullscreen) {
      element.requestFullscreen()
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen()
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen()
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen()
    }
  }

  // 退出全屏
  exitFullscreen() {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    }
  }

  // 美化布局
  // direction of the layout (one of "TB" (top-to-bottom) / "BT" (bottom-to-top) / "LR" (left-to-right) / "RL" (right-to-left))
  beautify(direction) {
    this.paper.freeze()
    joint.layout.DirectedGraph.layout(this.graph, {
      dagre: dagre,
      graphlib: graphlib,
      rankDir: direction,
      rankSep: 80,
      nodeSep: 80,
      edgeSep: 50,
      marginX: 100,
      marginY: 100
    })
    this.paper.unfreeze()
  }
  // 销毁
  destroy() {
    this.graph.destroy()
    this.paper.remove()
    if (this.stencil) {
      this.stencil.remove()
    }
    this.nav.remove()
    this.paperScroller.remove()
    this.commandManager.destroy()
    if (this.selection) {
      this.selection.remove()
    }
    this.snaplines.remove()
  }
 
  // 自动换行/腰圆
  breakedText(cell, text, val) {
    // 判断是拖拽还是输入 val=空时为拖拽
    if (val == '') {
      // 拖拽
      let _this = this
      let sizeData = cell.attributes.size
      let fontSize = cell.attributes.attrs.label.fontSize;//获取文字大小
      let c = cell.attributes.attrs
      // 腰圆形拖拽过程中动态设置圆角
      if (c.root.shape) {
        this.changeRx(cell, parseInt(sizeData.height * 0.5))
      };
      setTimeout(function () {//放置多次触发
        //  将文字内容，进行重新格式化
        let cellText = cell.attributes.attrs.label.text.replace(/\t\n/g, "")
        let line_size = cellText.split('\n')
        let textArr = []
        for (let i = 0; i < line_size.length; i++) {
         let breaked_text = joint.util.breakText(line_size[i], { width: sizeData.width - (20+ fontSize) }, { 'font-size': fontSize }, { eol: '\t\n' });
          textArr.push(breaked_text)
        }
        cell.attr('label/text', textArr.join('\n'))
      }, 500)
    } else {
      // 输入
      if (text.length != 0) {
        //  输入内容不为空时，将数据进行自动换行
        let sizeData = cell.attributes.size; //获取元素宽高
        let fontSize = cell.attributes.attrs.label.fontSize;//获取文字大小
        let cellText = text.replace(/\t\n/g, "")
        let line_size = cellText.split('\n')
        let textArr = []
        for (let i = 0; i < line_size.length; i++) {
          let breaked_text = joint.util.breakText(line_size[i], { width: sizeData.width - (50 + fontSize)}, { 'font-size': fontSize }, { eol: '\t\n' });
          textArr.push(breaked_text)
        }
        let textStr = textArr.join('\n')
        let line_num = textStr.split('\n').length;
        if (line_num != 1) {
          if (sizeData.height < fontSize * line_num + 30) {
            cell.resize(sizeData.width, fontSize * line_num + 30)
          }
        }
        cell.attr('label/text', textStr)
      } else {
        // 当输入内容为空时直接为空
        cell.attr('label/text', text)
      }
    }


  }
}
export default Workflow
